<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CourierCompany;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class CourierCompanyController extends Controller
{
    public function store(Request $request)
    {
        $company = CourierCompany::create($request->only(['name', 'sort_id']));
        \App\Services\CourierCompany::forgetCourierCompanyCache();

        return $this->response->created(null, $company);
    }

    public function delete($id)
    {
        CourierCompany::query()->find($id)->delete();
        \App\Services\CourierCompany::forgetCourierCompanyCache();

        return $this->response->noContent();
    }

    public function list(Request $request)
    {
        if ((int) $request->per_page === 999) {
            return $this->response->array(\App\Services\CourierCompany::getCourierCompanyByCache());
        }

        return $this->response->array(
            CourierCompany::query()
                ->when($request->get('name', ''), function (Builder $query, $name) {
                    $query->where('name', 'like', '%' . $name . '%');
                })
                ->paginate());
    }

    public function update(Request $request, $id)
    {
        $company = CourierCompany::query()->findOrFail($id);

        if ($name = $request->get('name')) {
            $company->name = $name;
        }
        if ($sortId = $request->get('sort_id')) {
            $company->sort_id = $sortId;
        }

        $company->save();
        \App\Services\CourierCompany::forgetCourierCompanyCache();

        return $this->response->created(null, $company);
    }
}
